package com.wuhao.code.check.ui

import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.InputValidator
import com.intellij.openapi.ui.Messages
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel

/**
 * Dialog widget relative
 * Created by Seal.wu on 2017/9/21.
 */
/** Json input Dialog */
private val inputValidator = object : InputValidator {

  override fun checkInput(p0: String?): Boolean {
    return true
  }

  override fun canClose(p0: String?): Boolean {
    return true
  }

}


/**
 * @author 吴昊
 * @date 2024/01/25
 * @version 1.0
 * @since v1.0.0
 */
class XmlResultDialog(
    project: Project,
) : Messages.InputDialog(
    project,
    "XMLLess生成结果",
    "生成结果仅供参考，静态解析结果和实际运行结果可能有所不同",
    null,
    "",
    inputValidator,
) {

  private lateinit var jsonContentEditor: Editor

  init {
    this.myField.isVisible = false
    this.cancelAction.putValue("Visible", false)
    setOKButtonText("确定")
    setCancelButtonText("取消")
  }

  override fun createCenterPanel(): JComponent {
    jsonContentEditor = createJsonContentEditor()
    return JPanel(BorderLayout()).apply {
      this.add(jsonContentEditor.component)
    }
  }

  override fun getInputString(): String = if (exitCode == 0) {
    jsonContentEditor.document.text.trim()
  } else {
    ""
  }

  override fun getPreferredFocusedComponent(): JComponent {
    return jsonContentEditor.contentComponent
  }

  fun setSql(sql: String) {
    this.jsonContentEditor.document.setReadOnly(false)
    this.jsonContentEditor.document.setText(sql)
    this.jsonContentEditor.document.setReadOnly(true)
  }

  private fun createJsonContentEditor(): Editor {
    val editorFactory = EditorFactory.getInstance()
    val document = editorFactory.createDocument("<script></script>").apply {
      setReadOnly(true)
    }
    val editor = editorFactory.createEditor(document, null, XmlFileType.INSTANCE, false)
    editor.component.apply {
      isEnabled = true
      preferredSize = Dimension(1000, 640)
      autoscrolls = true
    }
    val contentComponent = editor.contentComponent
    contentComponent.isFocusable = true
    return editor
  }

}
